/* eslint-disable arrow-body-style */
import React from 'react';
import { connect } from 'umi';
import { history } from 'umi';
import { Table, Card, Tag, Button, Form, Tooltip } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
// import { getOrganization } from '@/utils/utils.js'
import { getemployeelist } from '@/services/attendance/overtime';
// import { getQualityTag } from '../utils';
import Pagination from '@/components/Pagination';
import Detail from './Detail';
import Search from './Search';

const filtersTaskScore = [
    { text: '优', value: 4 },
    { text: '良', value: 3 },
    { text: '中', value: 2 },
    { text: '差', value: 1 },
    { text: '未评估', value: 5 }
];

const filtersTaskStatus = [
    { text: '完成', value: '完成' },
    { text: '处理中', value: '处理中' },
    { text: '待办', value: '待办' }
];

const filtersTaskCompleteStatus = [
    { text: '逾期', value: '逾期' },
    { text: '正常', value: '正常' }
];

const filtersMap = {
    taskStatus: filtersTaskStatus,
    taskCompleteStatus: filtersTaskCompleteStatus,
    scoreRank: filtersTaskScore
};

const Task = props => {
    const {
        dispatch,
        loading,
        workTask,
        form,
        location: { query = {}, pathname }
    } = props;

    const [detailVisible, setDetailVisible] = React.useState(false);
    const [detail, setDetail] = React.useState({});

    const getFilterValue = field => {
        const list = filtersMap[field];
        let value = workTask.query[field] || query[field];
        if (field === 'scoreRank') {
            value = parseInt(value, 10);
        }
        const exist = list.find(item => item.value === value);
        if (exist) {
            return [exist.value];
        }
        return [];
    };

    const getOrderValue = field => {
        const sortBy = workTask.query.sortBy || query.sortBy;
        if (sortBy) {
            const sortByInfo = sortBy.split(' ');
            if (field === sortByInfo[0]) {
                return `${sortByInfo[1]}end`;
            }
        }
        return '';
    };

    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};

    // const defaultCompanyId = user.companyId;
    const defaultCompanyId = 101;
    const getCurrentCompanyId = () => {
        if (form.getFieldValue('companyId')) {
            return form.getFieldValue('companyId');
        }
        return defaultCompanyId;
    };

    const fetchEmployeeList = React.useCallback(async () => {
        const response = await getemployeelist({ companyId: getCurrentCompanyId() });
        if (response.code === 10000) {
            const employeeNameList = [];
            response.data.forEach(item => {
                if (item.employeeName) {
                    employeeNameList.push(item.employeeName);
                }
            });
            dispatch({
                type: 'workTask/save',
                payload: { employeeNameList }
            });
        }
    });

    // 获取所有员工名字，用户员工搜索
    React.useEffect(() => {
        fetchEmployeeList();
        return () => {
            dispatch({
                type: 'workTask/save',
                payload: { employeeNameList: [] }
            });
        };
    }, [getCurrentCompanyId()]);

    /* 表格数据 */
    React.useEffect(() => {
        dispatch({
            type: 'workTask/fetch',
            payload: {
                ...query,
                companyId: defaultCompanyId,
                evalFlag: 1,
                ...workTask.query
            }
        });
    }, [workTask.query, query]);

    // 页面卸载时清理数据
    React.useEffect(() => {
        return () => {
            dispatch({
                type: 'workTask/clearAndPatchQuery',
                payload: {}
            });
        };
    }, []);

    /* 翻页 */
    const handlePageChange = React.useCallback(({ pageSize, current: pageNo }) => {
        const payload = {};
        if (pageSize) {
            payload.pageSize = pageSize;
        }
        if (pageNo) {
            payload.pageNo = pageNo;
        }
        dispatch({ type: 'workTask/patchQuery', payload });
    }, []);

    const onChangeTable = (pagination, filters, sorter) => {
        const extraQuery = {};
        let orderBy = '';
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'spentMinute') {
                sorterField = 'spent_minute';
            }
            const order = sorter.order.trim().split('end')[0];
            orderBy = `${sorterField} ${order}`;
        }
        extraQuery.sortBy = orderBy;

        if (filters && Object.keys(filters).length) {
            Object.keys(filters).forEach(item => {
                const [filterValue] = filters[item];
                if (item === 'evalScore') {
                    extraQuery.scoreRank = filterValue;
                } else {
                    extraQuery[item] = filterValue;
                }
            });
        }
        history.push({ pathname, query: { ...query, ...extraQuery } });
        dispatch({ type: 'workTask/patchQuery', payload: { ...extraQuery } });
    };

    const getColor = data => {
        if (data) {
            if (data.indexOf('正常') > -1) {
                return 'green';
            }
            return 'red';
        }
        return '';
    };

    const getHour = min => {
        if (min % 60 === 0) {
            return min / 60;
        }
        return (min / 60).toFixed(2);
    };

    const columns = [
        {
            title: '任务ID',
            dataIndex: 'taskNo',
            key: 'taskNo',
            width: 150
        },
        {
            title: '任务标题',
            dataIndex: 'taskName',
            key: 'taskName',
            width: 300,
            render: (text, record) => (
                <Tooltip placement="topLeft" title={text}>
                    <Button
                        type="link"
                        style={{
                            width: 300,
                            textAlign: 'left',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            padding: 0
                        }}
                        onClick={() => {
                            // 显示模态框以及查看员工的id
                            setDetail(record); // 接口还没实现，临时将整条记录传入
                            setDetailVisible(true);
                        }}
                    >
                        {text}
                    </Button>
                </Tooltip>
            )
        },
        // {
        //     title: '类型',
        //     dataIndex: 'taskType',
        //     key: 'taskType',
        //     width: 100
        // },
        {
            title: '责任人',
            dataIndex: 'employeeName',
            key: 'employeeName',
            width: 80,
            render: data => {
                const { reportType, companyId, startDate, endDate } = query;
                const queryData = {
                    reportType,
                    companyId,
                    startDate,
                    endDate,
                    employeeName: data
                };
                return (
                    <Button
                        type="link"
                        style={{ padding: 0 }}
                        onClick={() => {
                            history.push({
                                pathname: '/stat/workStat/workOverview/work/employee',
                                query: queryData
                            });
                        }}
                    >
                        {data}
                    </Button>
                );
            }
        },
        {
            title: '计划工作量',
            dataIndex: 'orginEstimateMinute',
            key: 'orginEstimateMinute',
            render: m => {
                const hour = getHour(m);
                return `${hour}小时`;
            }
        },
        {
            title: '实际工作量',
            dataIndex: 'spentMinute',
            key: 'spentMinute',
            sortOrder: getOrderValue('spent_minute'),
            sorter: true,
            render: m => {
                const hour = getHour(m);
                return m ? `${hour}小时` : '一一';
            }
        },
        // {
        //     title: '任务质量',
        //     dataIndex: 'evalScore',
        //     key: 'evalScore',
        //     filters: filtersTaskScore,
        //     filteredValue: getFilterValue('scoreRank'),
        //     filterMultiple: false,
        //     render: (data, record) => {
        //         const rt = getQualityTag(record.evalRank);
        //         return (
        //             <>
        //                 <span style={{ marginRight: 5 }}>{data && data.toFixed(2)}</span>
        //                 <Tag color={rt.color}>{rt.label}</Tag>
        //             </>
        //         );
        //     }
        // },
        {
            title: '完成状态',
            dataIndex: 'taskStatus',
            key: 'taskStatus',
            filters: filtersTaskStatus,
            filterMultiple: false,
            filteredValue: getFilterValue('taskStatus')
        },
        {
            title: '是否逾期',
            dataIndex: 'taskCompleteStatus',
            key: 'taskCompleteStatus',
            filters: filtersTaskCompleteStatus,
            filterMultiple: false,
            filteredValue: getFilterValue('taskCompleteStatus'),
            render: data => {
                return getColor(data) ? (
                    <Tag color={getColor(data)} style={{ borderStyle: 'dashed' }}>
                        {data}
                    </Tag>
                ) : (
                    '一一'
                );
            }
        },
        // {
        //     title: '公司',
        //     dataIndex: 'companyName',
        //     width: 100,
        //     key: 'companyName'
        // },
        {
            title: '产品线',
            dataIndex: 'productName',
            key: 'productName',
            ellipsis: true
        },
        {
            title: '项目组',
            dataIndex: 'projectGroupName',
            key: 'projectGroupName',
            render(text) {
                return (
                    <div
                        title={text}
                        style={{
                            width: 200,
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis'
                        }}
                    >
                        {text}
                    </div>
                );
            }
        }
    ];
    return (
        <PageHeaderWrapper>
            <Detail
                visible={detailVisible}
                data={detail}
                onClose={() => {
                    setDetailVisible(false);
                }}
            />
            <Card>
                <div style={{ marginBottom: 24 }}>
                    <Search {...props} defaultCompanyId={defaultCompanyId} user={user} />
                </div>
                <Table
                    rowKey="taskNo"
                    columns={columns}
                    dataSource={workTask.dataSource}
                    onChange={onChangeTable}
                    pagination={false}
                    loading={loading}
                    scroll={{ x: 'max-content' }}
                />
                <Pagination
                    total={workTask.total}
                    current={workTask.query.pageNo}
                    pageSize={workTask.query.pageSize}
                    onChange={handlePageChange}
                />
            </Card>
        </PageHeaderWrapper>
    );
};

const mapStateToProps = ({ workTask, loading }) => ({ loading: loading.effects['workTask/fetch'], workTask });

export default connect(mapStateToProps)(Form.create({ name: 'Search' })(Task));
